#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
    pid_t pid;
    if((pid = fork()) < 0){
        printf("fork error!\n");
        exit(0);
    }else if(pid == 0){
        if((pid = fork()) < 0){
            printf("fork error!\n");
            exit(0);
        }else if(pid > 0){
            printf("second fork exit\n");
            exit(0);    //将子进程托管给init进行回收
        }

        //等待父进程结束，这样保证自己在执行期间是init的子进程
        //这种形式称为轮询，他的问题是浪费了CPU时间
        //为了避免竞争条件和轮询，在进程之间需要有某种的信号发送和接收的方法
        while(getppid() != 1){
            sleep(1);
        }
        printf("third fork exit, parent pid: %d\n", getppid());
        exit(0);
    }

    if(waitpid(pid, NULL, 0) != pid){
        printf("waitpid error!\n");
        exit(0);
    }
    while(1){
        printf("do my job\n");
        sleep(10);
    }
    printf("first pid exit, pid: %d\n", getpid());

    if((pid = fork()) < 0){
        printf("fork error!\n");
        exit(0);
    }else if(pid == 0){
        printf("forth pid execut: %d\n", getpid());
        sleep(10);
    }

    exit(0);
}